<?php

namespace App\Admin\Http\Controllers\Web;

use App\Admin\Eloquent\Profit;
use App\Admin\Eloquent\ProfitRole;
use App\Admin\Http\Requests\ProfitRequest;
use App\Extensions\Pagination\BootstrapThreePresenter;
use Flash;
use App\Exceptions\BusinessException;
use App\Admin\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class ProfitsController extends Controller
{
  /** 分润规则列表
   *  @return \Illuminate\Http\Response
   */
  public function index( )
  {
    $profits = Profit::orderBy('created_at','desc')->paginate(15);
    $stages = Profit::getStages();

    // 分页
    $links = (new BootstrapThreePresenter($profits))->render();

    return view('admin.web.profits.index', compact('profits', 'stages', 'links'));
  }
  /**
   * 新增分润表单
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    //动态获取数据库字典表
    // 角色 阶段 方式
    $roles = Profit::getRoles();
    $stages = Profit::getStages();
    $modes = Profit::getModes();

    //允许填写的
    $arr=array(
      'profits_stage_one'=>['OperatingPlatform','MarketingAgency','GuaranteeAgency'],
      'profits_stage_two'=>['User'],
    );

    return view('admin.web.profits.create', compact('roles', 'stages', 'modes','arr'));
  }

  /**
   * 新增分润规则表单
   *
   * @param ProfitRequest $request
   * @return \Illuminate\Http\RedirectResponse
   */
  public function store(ProfitRequest $request)
  {
    //创建分润规则对象
    $arr = $request->input();
    //获取字典表中所有分润阶段
    $stages = Profit::getStages();

    foreach($stages as $stage){
      $profit_stage[] = $stage->code;
    }
    //将字典表中所有分润阶段存入
    $arr['stage'] =implode(',', $profit_stage);
    $profit = new Profit($arr);

    //开启事务
    DB::beginTransaction();

    try{
      if ($profit->save()){
        //获取分润规则对象的id
        $id = $profit->id;
        $roles = Profit::getRoles();

        foreach($stages as $stage) {
          //创建分润角色
          foreach ($roles as $role) {
            $profit_role = new ProfitRole();
            //使用分润表的id 关联分润规则表
            $profit_role->profit_id = $id;
            $profit_role->stage = $stage->code;
            $profit_role->role = $role->code;
            //获取页面 角色的比例值 命名规则为 阶段code+角色code
            $profit_role->scale = $arr[$stage->code.'-'.$role->code];

            if (!$profit_role->save()){
              Flash::error('新增分润规则记录失败');
              return $this->redirectAction('Web\ProfitsController@index');
            }
          }
        }
        //提交事务
        DB::commit();
        Flash::success('新增分润规则记录成功');

        return $this->redirectAction('Web\ProfitsController@index');
      } else{
        Flash::error('新增分润规则记录失败');

        return $this->redirectAction('Web\ProfitsController@index');
      }
    }catch (\Exception $e){
      //回滚事务
      DB::rollback();

      Flash::error('新增分润规则记录失败');

      return $this->redirectAction('Web\ProfitsController@index');
    }
  }

  /**
   * 根据id删除分润规则
   *
   * @param int $id
   * @return \Illuminate\Http\Response
   */
  public function destroy($id)
  {

    $profit = Profit::findOrFail($id);
    if($profit->isUsed($id)){

      Flash::error('删除分润规则失败。该规则正在被使用，无法删除');

      return $this->redirectAction('Web\ProfitsController@index');
    }

    if ($profit->delete()){

      ProfitRole::where('profit_id',$profit->id)->delete();

      Flash::success('删除分润规则成功');

      return $this->redirectAction('Web\ProfitsController@index');
    } else{
      Flash::error('删除分润规则失败');

      return $this->redirectAction('Web\ProfitsController@index');
    }
  }


  /**
   * 编辑分润规则表单
   *
   * @param int $id
   * @return \Illuminate\Http\Response
   */
  public function edit(int $id)
  {
    $profit = Profit::findOrFail($id);

    $profit_roles = ProfitRole::where('profit_id',$profit->id)->get()->sort();

    //动态获取数据库字典表
    //  阶段 方式
    $stages = Profit::getStages();
    $modes = Profit::getModes();

    //允许填写的
    $arr=array(
      'profits_stage_one'=>['OperatingPlatform','MarketingAgency','GuaranteeAgency'],
      'profits_stage_two'=>['User'],
    );

    return view('admin.web.profits.edit', compact('profit', 'stages', 'modes', 'profit_roles','arr'));
  }

  /**
   * 修改分润规则表单
   *
   * @param ProfitRequest $request
   * @param int $id
   * @return \Illuminate\Http\Response
   * @throws BusinessException
   */
  public function update(ProfitRequest $request,int $id)
  {
    $arr = $request->input();

    $profit = Profit::findOrFail($id);

    //判断该规则是否被使用
    if($profit->isUsed($id)){
      Flash::error('修改分润规则失败。该规则正在被使用，无法修改');

      return $this->redirectAction('Web\ProfitsController@index');
    }
    //开启事务
    DB::beginTransaction();

    try {
      if ($profit->update($arr)) {

        //获取所有分润角色信息
        $profit_roles = ProfitRole::query()->where('profit_id', $id)->get();
        foreach ($profit_roles as $profit_role) {
          //获取页面的值 并改变原有的值
          $profit_role->scale = $arr[$profit_role->stage . '-' . $profit_role->role];

          if (!$profit_role->update()){

            Flash::error('修改分润规则失败');
            return $this->redirectAction('Web\ProfitsController@index');
          }
        }

        //提交事务
        DB::commit();

        Flash::success('修改分润规则成功');

        return $this->redirectAction('Web\ProfitsController@index');
      } else {
        Flash::error('修改分润规则失败');

        return $this->redirectAction('Web\ProfitsController@index');
      }
    }catch (\Exception $e){
      //回滚事务
      DB::rollback();

      Flash::error('修改分润规则失败');

      return $this->redirectAction('Web\ProfitsController@index');
    }
  }

  /**
   * 根据id查看分润规则
   *
   * @param int $id
   * @return \Illuminate\Http\Response
   */
  public function show(int $id)
  {
    $profit = Profit::findOrFail($id);
    $stages = Profit::getStages();
    $profit_roles = ProfitRole::where('profit_id',$profit->id)->get()->sort();

    return view('admin.web.profits.show', compact('profit', 'stages', 'profit_roles'));
  }
  /**
   * 根据id禁用分润规则
   *
   * @param int $id
   * @return \Illuminate\Http\RedirectResponse
   */
  public function disable($id)
  {
    $profit = Profit::findOrFail($id);

    //判断该规则是否被禁用
    //如果被禁用 则启用 反之 禁用
    $profit->state = !$profit->state;

    if ($profit->save()){
      Flash::success( $profit->state?'启用分润规则成功': '禁用分润规则成功' );

      return $this->redirectAction('Web\ProfitsController@index');
    } else{
      Flash::error('更改失败');

      return $this->redirectAction('Web\ProfitsController@index');
    }
  }

}